<?php
/**
 * Created by PhpStorm.
 * User: kun
 * Date: 26/6/19
 * Time: 18:20
 */

namespace app\api\controller;


use app\common\lib\exception\ApiException;
use app\common\lib\IAuth;
use app\common\lib\Time;
use Qiniu\Auth;
use think\Cache;
use think\Controller;
use app\common\lib\Aes;

/*
 * API 模块公共控制器
 */

class Common extends Controller
{
    /**
     * $headers 信息
     * @var string
     */
    public $headers = '';

    /**
     * 页数
     * page
     * @var string
     */
    public $page = '';

    /**
     * 每页显示多少条
     * @var string
     */
    public $size = '';
    /**
     * 查询条件的起始值
     * @var int
     */
    public $from = 0;

    /**
     * 初始化的方法
     */
    public function _initialize()
    {
        $this->checkRequestAuth();
//        $this->testAes();
    }

    /**
     * 检查每次APP请求是否合法
     * @throws ApiException
     */
    public function checkRequestAuth()
    {
        $headers = request()->header();
        if (empty($headers['sign'])) {
            throw new ApiException('sing不存在', 400);
        }
        if (!in_array($headers['apptype'], config('app.apptypes'))) {
            throw new ApiException('apptype客户端类型不合法', 400);
        }

        //sign

        if (!IAuth::checkSignPass($headers)) {
            throw new ApiException('授权码sign失败', 401);
        }

        Cache::set($headers['sign'], 1, config('app.app_sign_cache_time'));

        $this->headers = $headers;

    }


    //测试
    public function testAes()
    {

        $data = [
            'did' => '1234',
            'version' => 1,
            'time' => Time::get13TimeStamp(),
        ];

        echo IAuth::serSing($data);
        exit();

    }

    /**
     * 获取处理新闻的内容数据
     * @param array $news
     * @return array
     */
    protected function getDealNews($news = [])
    {
        if (empty($news)) {
            return [];
        }
        $cats = config('cat.lists');
        foreach ($news as $key => $new) {
            $news[$key]['catname'] = $cats[$new['catid']] ? $cats[$new['catid']] : '-';
        }

        return $news;

    }


    /**
     * 获取分页page size 内容
     */
    public function getPageAndSize($data)
    {
        $this->page = !empty($data['page']) ? $data['page'] : 1;
        $this->size = !empty($data['size']) ? $data['page'] : config('paginate.list_rows');
        $this->from = ($this->page - 1) * $this->size;
    }


}